import 'package:flutter/material.dart';
import 'package:rainflutter/main.dart';

class InheritedChangeTest extends StatelessWidget {
  final Image image = Image.asset('assets/images/calendar_spring.png');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('InheritedChangeTest')),
      body: Center(
          child: Column(
        children: [
          StlessBox(),
          ImageBox(),
          OutlineButton(
            onPressed: () {
              // Navigator.pop(context);
            },
            child: Text('上一步'),
          ),
          InheritedWidgetTestRoute(),
          InheritedImageWidget(
            imageUrl: 'assets/images/calendar_autumn.png',
            child: Column(
              children: [image],
            ),
          )
        ],
      )),
    );
  }
}

class StlessBox extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Image nose =
    //     context.dependOnInheritedWidgetOfExactType<InheritedNose>().asset;

    // nose = Image.asset('assets/images/calendar_summer.png');
    LoginState loginState = InheritedLoginWidget.of(context).loginState;

    print('StlessBox-build');
    return Container(
      child: TextButton(
        child: Text(loginState.isLogin ? '登录' : '未登录'),
        onPressed: () {
          print('更新数据');
          loginState.isLogin = !loginState.isLogin;
        },
      ),
    );
  }
}

class ImageBox extends StatefulWidget {
  @override
  _ImageBoxState createState() => _ImageBoxState();
}

class _ImageBoxState extends State<ImageBox> {
  //注意顺序
  String imageUrl = 'assets/images/calendar_summer.png';
  @override
  Widget build(BuildContext context) {
    // Image nose =
    //     context.dependOnInheritedWidgetOfExactType<InheritedNose>().asset;

    // nose = Image.asset('assets/images/calendar_summer.png');
    // String netImageUrl =
    //     "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201403%2F02%2F092241w9f4vaz8peovfe91.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617171292&t=b841f99b45f0beae202712d143ff6101";

    // Image image = Image.network(netImageUrl);

    print('StlessBox-build');
    return InheritedImageWidget(
      imageUrl: imageUrl,
      child: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            _ImageWiget(),
            Row(
              children: [
                OutlineButton(
                  child: Text('春'),
                  onPressed: () {
                    print('更新数据');

                    setState(() {
                      imageUrl = 'assets/images/calendar_spring.png';
                    });
                  },
                ),
                OutlineButton(
                  child: Text('夏'),
                  onPressed: () {
                    print('更新数据');

                    setState(() {
                      imageUrl = 'assets/images/calendar_summer.png';
                    });
                  },
                ),
                OutlineButton(
                  child: Text('秋'),
                  onPressed: () {
                    print('更新数据');

                    setState(() {
                      imageUrl = 'assets/images/calendar_autumn.png';
                    });
                  },
                ),
                OutlineButton(
                  child: Text('冬'),
                  onPressed: () {
                    print('更新数据');

                    setState(() {
                      imageUrl = 'assets/images/calendar_winter.png';
                    });
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class InheritedImageWidget extends InheritedWidget {
  final String imageUrl;
  InheritedImageWidget({this.imageUrl, Widget child}) : super(child: child);

  static InheritedImageWidget of(BuildContext context) =>
      context.dependOnInheritedWidgetOfExactType<InheritedImageWidget>();

  @override
  bool updateShouldNotify(InheritedImageWidget oldWidget) {
    return oldWidget.imageUrl != imageUrl;
  }
}

class _ImageWiget extends StatefulWidget {
  @override
  __ImageWigetState createState() => __ImageWigetState();
}

class __ImageWigetState extends State<_ImageWiget> {
  @override
  Widget build(BuildContext context) {
    print(InheritedImageWidget.of(context).imageUrl);
    return SizedBox(
        width: double.infinity,
        height: 100,
        child: Image.asset(InheritedImageWidget.of(context).imageUrl));
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("_ImageWiget Dependencies change");
  }
}

//-------------#-----------

class InheritedWidgetTestRoute extends StatefulWidget {
  @override
  _InheritedWidgetTestRouteState createState() =>
      new _InheritedWidgetTestRouteState();
}

class _InheritedWidgetTestRouteState extends State<InheritedWidgetTestRoute> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ShareDataWidget(
        //使用ShareDataWidget
        data: count,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 20.0),
              child: _TestWidget(), //子widget中依赖ShareDataWidget
            ),
            RaisedButton(
              child: Text("Increment"),
              //每点击一次，将count自增，然后重新build,ShareDataWidget的data将被更新
              onPressed: () => setState(() => ++count),
            )
          ],
        ),
      ),
    );
  }
}

class ShareDataWidget extends InheritedWidget {
  ShareDataWidget({@required this.data, Widget child}) : super(child: child);

  final int data; //需要在子树中共享的数据，保存点击次数

  //定义一个便捷方法，方便子树中的widget获取共享数据
  static ShareDataWidget of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
  }

  //该回调决定当data发生变化时，是否通知子树中依赖data的Widget
  @override
  bool updateShouldNotify(ShareDataWidget old) {
    //如果返回true，则子树中依赖(build函数中有调用)本widget
    //的子widget的`state.didChangeDependencies`会被调用
    return old.data != data;
  }
}

class _TestWidget extends StatefulWidget {
  @override
  __TestWidgetState createState() => new __TestWidgetState();
}

class __TestWidgetState extends State<_TestWidget> {
  @override
  Widget build(BuildContext context) {
    //使用InheritedWidget中的共享数据
    return Text(ShareDataWidget.of(context).data.toString());
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //父或祖先widget中的InheritedWidget改变(updateShouldNotify返回true)时会被调用。
    //如果build中没有依赖InheritedWidget，则此回调不会被调用。
    print("Dependencies change");
  }
}
